package base;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlUtil {
	/**
	 * 将数据写到xml文件中
	 * @param file	xml文档的路径
	 * @param document	xml文档：传入形参
	 * @throws Exception
	 */
	public static void writeToXml(String file,Document document) throws Exception{
		PrintWriter pw = new PrintWriter(file);
//		OutputFormat format = BookUtil.myFormat();
		
		//设置xml文档的编码格式 myFormat()
		XMLWriter xw = new XMLWriter(pw, myFormat());
		xw.write(document);
		xw.flush();
		xw.close();
		System.err.println("导出成功...");
	}
	
	/**
	 * 采用SAXReader的解析方式：从xml中读取数据
	 * @param filePath	xml文档路径
	 * @throws Exception
	 */
	public static Document readerXml(String filePath) throws Exception{
		//采用SAXReader的解析方式：
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(filePath));
		
		//1.创建StringWriter对象：保存xml文档
		StringWriter writer = new StringWriter();
		
		//2.设置解析xml文档的编码格式 myFormat()
		XMLWriter xmlwriter = new XMLWriter(writer, myFormat());
		
		//3.把xml文档装换为 String
		xmlwriter.write(document);
		
		//打印
//		System.out.println(document.asXML());
		xmlwriter.close();
		return document;
	}
	
	/**
	 * 设置xml文档转换格式
	 * 	--直接调用static OutputFormat.createCompactFormat()方法
	 */
	public static OutputFormat myFormat(){
//		OutputFormat format = OutputFormat.createPrettyPrint();   //自动缩进
		OutputFormat format = OutputFormat.createCompactFormat();	
		format.setEncoding("utf-8");	//指定编码方式
		format.setIndent(true);			//设置是否缩进
		format.setIndent("\t");			//设置（每个子节点）缩进4个空格
        format.setNewlines(true);		//设置是否换行
        return format;
	}
}
